<?php

namespace App\Console\Commands\Invoice;

use App\Models\Invoice\InvoiceHistoryModel;
use App\Remote\MoreDo\InvoiceRemote;
use App\Service\Invoice\InvoiceService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Validation\ValidationException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class InitInvoiceStatusCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'invoice:initInvoiceStatus';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '主动同步发票信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function handle(): int
    {
        InvoiceHistoryModel::query()->where(function ($query) {
            $query->where(function ($query) {
                $query->where("status", InvoiceHistoryModel::STATUS_1)->where("blueInvoiceNumber", "<>", "");
            })->orWhere(function ($query) {
                $query->where("status", InvoiceHistoryModel::STATUS_4)->where("redConfirmSerialNo", "<>", "");
            });
        })->chunkById(20, function (Collection $collection) {
            $collection->each(function (InvoiceHistoryModel $invoiceHistoryModel) {
                $this->output->info($invoiceHistoryModel->only(["id", "orderId"]));
                try {
                    switch ($invoiceHistoryModel->status) {
                        case InvoiceHistoryModel::STATUS_1:
                            //蓝票业务处理
                            $detail = InvoiceRemote::getInvoice($invoiceHistoryModel->orderId);
                            InvoiceService::notify((object)$detail);
                            break;
                        case InvoiceHistoryModel::STATUS_4:
                            //红票业务处理
                            $detail = InvoiceRemote::getInvoice($invoiceHistoryModel->orderId, 1);
                            InvoiceService::notify((object)$detail);
                            break;
                    }
                } catch (\Exception $exception) {
                    logException("主动拉取处理数据失败", $exception, $invoiceHistoryModel->only(["id", "orderId"]), true, true);
                }

            });
        });

        return 0;
    }
}
